# -*- coding: utf-8 -*-
'''eof
name:企业近2年贸易融资贷款笔数
code:EC13_Past2YearsTFLoanCnts_2D
tableName:
columnName:
groups:企业征信校验
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

'''
FACTOR = 针对所有的借贷账户（EDA ），筛选出在基本信息段（ED01A）中开立日期（ED01AR01）
在[当前时间-720,当前时间)之间、借贷业务种类大类（ED01AD05）为贸易融资（码值为12）的账户，
进行计数；
'''

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import datetime
from dateutil.relativedelta import relativedelta 
from dateutil.parser import parse

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
    获取表信息
    :param data:表上层的字典对象
    :param tableName:表的名字
    :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
    :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
    :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
    '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]
    
def EC13_Past2YearsTFLoanCnts_2D():
    data = EC_DSJ_2D.get('data')
    # 借贷账户信息
    EDA = getTable(data, 'EDA', 1, 0)
    if EDA == [{}]:
        return u'缺失值'
    elif EDA == 0:
        return 0
    else:
        ED01 = getTable(EDA[0], 'ED01', 0, 1)
        if ED01 == [{}]:
            return u'缺失值'
        elif ED01 == 0:
            return 0
        else:
            factor = []
            ED01_cont = 0
            nowTime = datetime.datetime.now().date()
            twoYearStratTime = nowTime - relativedelta(days = 720)
            for i in ED01:
                try:
                    # 基本信息段
                    ED01A = getTable(i, 'ED01A', 1, 1)
                    if ED01A == [{}]:
                        ED01_cont += 1
                        factor.append(None)
                    elif ED01A == 0:
                        factor.append(0)      
                    else:
                        # 借贷业务种类
                        ED01AD05 = ED01A[0].get("ED01AD05")
                        #账户开立时间
                        ED01AR01 = parse(ED01A[0].get("ED01AR01")).date()
                        if ED01AD05 not in null_type_list and ED01AR01 not in null_type_list:
                            if ED01AD05 in [12,"12"] and twoYearStratTime <= ED01AR01 < nowTime:
                                factor.append(1)
                            else:
                                factor.append(0)  
                        else:
                            factor.append(None)
                            ED01_cont +=1
                except:
                    ED01_cont += 1
                    factor.append(None)
        if ED01_cont== len(ED01):
            return u'缺失值'
        factor = filter(lambda x:x is not None, factor)       
        return sum(factor)
    
result = EC13_Past2YearsTFLoanCnts_2D()
    